package com.ma.controller;
import cn.hutool.core.lang.Assert;
import com.github.pagehelper.PageInfo;
import com.ma.common.dto.PassDto;
import com.ma.common.dto.SysUserDto;
import com.ma.common.lang.Const;
import com.ma.common.lang.Result;
import com.ma.entity.SysRole;
import com.ma.entity.SysUser;
import com.ma.entity.SysUserRole;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Controller
@ResponseBody
@RequestMapping("/sys/user")
public class SysUserController extends BaseController {

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;
    /*
        查询用户信息
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public Result list(@RequestParam(value = "username",required = false)String username,
                       @RequestParam(value = "current",defaultValue = "1")  Integer page,
                       @RequestParam(value = "size",defaultValue = "10")  Integer rows){
        if (page <=1){
            page=1;
        }

        List<SysUser> sysUsers = sysUserService.listByUsername(username, page, rows);

        List<SysUserDto> sysUserDtos=new ArrayList<>();

        for (SysUser sysUser : sysUsers) {
            List<SysRole> sysRolesList=sysRoleService.getAllByUserId(sysUser.getId());

            SysUserDto sysUserDto=new SysUserDto();
            sysUserDto.setSysRole(sysRolesList);

            sysUserDto.setId(sysUser.getId());
            sysUserDto.setUsername(sysUser.getUsername());
            sysUserDto.setPassword(sysUser.getPassword());
            sysUserDto.setAvatar(sysUser.getAvatar());
            sysUserDto.setEmail(sysUser.getEmail());
            sysUserDto.setCity(sysUser.getCity());
            sysUserDto.setCreated(sysUser.getCreated());
            sysUserDto.setUpdated(sysUser.getUpdated());
            sysUserDto.setLastLogin(sysUser.getLastLogin());
            sysUserDto.setStatu(sysUser.getStatu());

           sysUserDtos.add(sysUserDto);
        }
        PageInfo<SysUserDto> pageInfo=new PageInfo<SysUserDto>(sysUserDtos);
        return Result.succ(pageInfo);
    }

    /*
        根据id查询用户信息
     */
    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public Result info(@PathVariable(value = "id")Long id){
        SysUser sysUser=sysUserService.getUserById(id);
        //使用断言机制  一旦为空就抛出IllegalArgumentException异常 由全局异常GlobalExceptionHandler捕获
        Assert.notNull(sysUser,"找不到该管理员");

        SysUserDto sysUserDto=new SysUserDto();
        List<SysRole> sysRolesList=sysRoleService.getAllByUserId(id);

        sysUserDto.setSysRole(sysRolesList);

        sysUserDto.setId(sysUser.getId());
        sysUserDto.setUsername(sysUser.getUsername());
        sysUserDto.setPassword(sysUser.getPassword());
        sysUserDto.setAvatar(sysUser.getAvatar());
        sysUserDto.setEmail(sysUser.getEmail());
        sysUserDto.setCity(sysUser.getCity());
        sysUserDto.setCreated(sysUser.getCreated());
        sysUserDto.setUpdated(sysUser.getUpdated());
        sysUserDto.setLastLogin(sysUser.getLastLogin());
        sysUserDto.setStatu(sysUser.getStatu());


        return Result.succ(sysUserDto);
    }

    /*
        更新用户信息
     */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:user:update')")
    public Result update(@Validated @RequestBody SysUser sysUser){
        sysUser.setUpdated(new Date());
        sysUserService.update(sysUser);
        return Result.succ("更新成功");
    }
    /*
           添加用户信息
        */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:user:save')")
    public Result save(@Validated @RequestBody SysUser sysUser){
        sysUser.setCreated(new Date());
        //默认密码并加密
        sysUser.setPassword(bCryptPasswordEncoder.encode(Const.DEFULT_PASSWORD));
        //默认头像
        sysUser.setAvatar(Const.DEFULT_AVATAR);
        sysUserService.save(sysUser);
        return Result.succ("添加成功");
    }
    /*
      删除用户信息
   */
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('sys:user:delete')")
    @Transactional
    public Result delete(@RequestBody Long[] ids){
        for (Long id : ids) {
            sysUserService.deleteUserById(id);
            sysUserRoleService.deleteUserByUserId(id);

        }

        return Result.succ("删除成功");
    }

    /*
      重置用户密码为初始值
   */

    @PostMapping("/repass")
    @PreAuthorize("hasAuthority('sys:user:repass')")
    public Result repass(@RequestBody Long id){
        SysUser sysUser = sysUserService.getUserById(id);
        sysUser.setPassword(bCryptPasswordEncoder.encode(Const.DEFULT_PASSWORD));
        sysUser.setUpdated(new Date());
        sysUserService.repassByUserId(sysUser);
        return Result.succ("重置成功");
    }

    /*
      为用户赋予角色
   */
    @Transactional
    @PostMapping("/role/{userId}")
    @PreAuthorize("hasAuthority('sys:user:role')")
    public Result rolePerm(@PathVariable(value = "userId")Long userId,@RequestBody Long[] rolesId){
        List<SysUserRole> sysUserRoles=new ArrayList();

        for (Long roleId : rolesId) {
            SysUserRole sysUserRole=new SysUserRole();
            sysUserRole.setRoleId(roleId);
            sysUserRole.setUserId(userId);

            sysUserRoles.add(sysUserRole);
        }
        sysUserRoleService.deleteUserByUserId(userId);
        for (SysUserRole sysUserRole : sysUserRoles) {
            sysUserRoleService.save(sysUserRole);
            //清空缓存
            SysUser userById = sysUserService.getUserById(sysUserRole.getUserId());
            sysUserService.clearUserAuthorityInfo(userById.getUsername());
        }
        return Result.succ("赋予权限成功");
    }

      /*
      重置用户密码为初始值
   */

    @PostMapping("/updatePass")
    public Result updatePass(@Validated @RequestBody PassDto passDto, Principal principal){
        SysUser user = sysUserService.getAllByUsername(principal.getName());
        //判断密码是否一致
        boolean matches = bCryptPasswordEncoder.matches(passDto.getCurrentPass(), user.getPassword());

        if (!matches){
            return Result.fail("旧密码不正确");
        }

        String encode = bCryptPasswordEncoder.encode(passDto.getPassword());

        user.setPassword(encode);
        user.setUpdated(new Date());

        sysUserService.update(user);

        return Result.succ("密码修改正确");
    }
}
